<?php

namespace app\api\controller;

use plugin\saiadmin\exception\ApiException;
use app\service\WechatService;
use app\service\JwtService;
use support\Request;
use support\Response;
use app\ai\model\User;
use plugin\saiadmin\app\logic\system\SystemConfigLogic;
use plugin\saiadmin\utils\Arr;
use app\ai\model\BalanceLog;
class LoginController
{
    /**
     * 微信小程序登录
     * @param Request $request
     * @return Response
     */
    public function wxLogin(Request $request)
    {
        try {
            $code = $request->post('code');
            if (empty($code)) {
                throw new ApiException('code不能为空');
            }

            // 调用微信登录服务获取openid等信息
            $wxLoginInfo = WechatService::login($code);
            $user = User::where('openid', $wxLoginInfo['openid'])->find();
            
            //如果查询不到user 就创建
            if (!$user) {
                //获取首次注册配置
                $logic = new SystemConfigLogic();
                $config = $logic->getGroup('task_config');
                if (!$config) {
                    throw new ApiException('未设置任务配置');
                }
                $sign_coin = Arr::getConfigValue($config, 'sign_coin');
                //创建用户
                $user = User::create([
                    'openid' => $wxLoginInfo['openid'],
                    'nickname' => '微信用户',
                    'avatar' =>  'https://static.kukuit.cn//upload/1294de4a9f61eac5479c2592f69ab373.jpeg',
                    'reg_ip' => $request->getRealIp(),
                    'last_login_time' => date('Y-m-d H:i:s'),
                    'sign_coin' => $sign_coin,
                    'coin_balance' => $sign_coin,
                    'level'=>1,
                    'status'=>1
                ]);
                //创建记录
                BalanceLog::create([
                    'user_id' => $user->id,
                    'price' => $sign_coin,
                    'before' => 0,
                    'after' => $sign_coin,
                    'type' => 1,
                    'remarks' => '注册赠送金币'
                ]);

            } else {
                // 更新最后登录时间
                $user->last_login_time = date('Y-m-d H:i:s');
                $user->save();
            }

            // 生成token
            $token = JwtService::generateToken($user->toArray());
            
            return json([
                'code' => 200,
                'msg' => '登录成功',
                'data' => [
                    'token' => $token,
                    'openid' => $user['openid'],
                    'nickName' => $user['nickname'],
                    'avatarUrl' => $user['avatar'],
                    'coin_balance' => $user['coin_balance'],
                    'diamond_balance' => $user['diamond_balance'],
                    'status' => $user['status'],
                    'level' => $user['level'],
                    'discount' => $user['discount'],
                    'level_endtime' => $user['level_endtime'],
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }
}
